// 单链表实现队列
public class MyQueue extends MyNullException{
    static class Node{
        public int val;
        public Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    public Node head;
    public Node tail;

    /**
     * 入队
     * add与offer的区别
     * @param val
     */
    public void offer(int val){
        Node node = new Node(val);
        if (isEmpty()){
            head = node;
            tail = node;
        }else {
            tail.next = node;
            tail = tail.next;
        }
    }

    /**
     * 出队
     * @return
     */
    public int poll(){
        if (isEmpty()){
            throw new MyNullException("当前队列为空,出队失败!");
        }
        int ret = head.val;
        if (head.next == null){
            head = null;
            tail = null;
        }else {
            head = head.next;
        }
        return ret;
    }

    /**
     * 查看队头元素
     * @return
     */
    public int peek(){
        if (isEmpty()){
            throw new MyNullException("当前队列为空,查看失败!");
        }
        return head.val;
    }

    public boolean isEmpty(){
        return head == null;
    }

    public int size(){
        int ret = 0;
        Node cur = head;
        while (cur != null){
            ret++;
            cur = cur.next;
        }
        return ret;
    }
}
